<style scoped>
.cart_row{align-items: stretch;background: #fff;margin: 6px auto;width: 350px;border-radius: 13px;padding: 8px;}
.cart_row>.select{padding: 0 5px;}
.cart_row>.img{width: 100px;height: auto;}
.cart_row>.content{flex-direction: column;align-items: stretch;padding: 1px 4px 1px 8px;}
.cart_row .price{text-align: right;color: #ff9200;font-weight: bold;}
.cart_row .price>.sm{font-size: 0.7em;}
.cart_row .sales{text-align: right;opacity: 0.8;font-size: 0.8em;}
</style>
<template>
  <div class="cart_list">
    <div class="cart_row flex" v-for="(row,i) in list">
      <van-checkbox v-model="row.status_bool" @change="on_change(row, i,{status_bool: row.status_bool})" :disabled="switch_stock && row.stock<=0"></van-checkbox>
      <cart_row class="max" :link_table="this.link_table" :title="row.title" :head_img="row.head_img" :price="row.price" :compute_price="row.compute_price"
                v-model:num="row.num" v-model:sku_id="row.sku_id" v-model:additional_select="row.additional_select" @change="on_change(row, i, $event)" ></cart_row>
    </div>
  </div>
  <FooterSlot>
    <footer-cart v-bind="cart_menu" show-select :select="!!cart_menu.allon" @update:select="all_select" @buy="buy" ></footer-cart>
  </FooterSlot>
</template>

<script>
import {msg} from "@/js/vant_tool.js";
import {S94Cart} from "@/js/S94Cart.js";
import cart_row from "@/components/cart/cart_row.vue";
import {ajax} from "@/js/api_tool.js";
import {_get, href_handle} from "@/vue_plugin/router_auto.js";
import FooterSlot from "@/components/slot/FooterSlot.vue";
import FooterCart from "@/components/cart/FooterCart.vue";
import {S94Model} from "@/js/S94Model.js";

export default {
  components: {FooterCart, FooterSlot, cart_row},
  data(){
    return {
      model_name: _get("model_name"),
      link_table: _get("link_table"),
      action: _get("action", "add"),
      switch_stock: false,
      list: [],
      count: 0,
      loading: false,
      finished: false,

      change_ing: false,
      compute_price_json: '', //计算价格请求参数的json，用于避免重复不必要的请求
      ban_change: true,

      cart_menu: {},
    }
  },
  methods:{
    init(){
      let url = `/home/cart/list?model_name=${this.model_name}&link_table=${this.link_table}`
      ajax(url, (res)=>{
        this.list = res.data.list;
        this.list.forEach(row=>{
          row.status_bool = (row.status==1);
          row.num_copy = row.num;
          let info = {};
          try {
            info = JSON.parse(row.info_json);
          } catch (e) { }
          row.additional_select = info.additional_select || {}
        })
        if (this.switch_stock){
          res.data.list.forEach((v)=>{
            if (v.stock > 0) this.count++;
          })
        }else{
          this.count = this.list.length;
        }
        this.compute_price();
        return false;
      })
    },
    edit(ids, data){
      return new Promise((resolve, reject) => {
        ajax({url:`/home/cart/edit?ids=${ids}`, data:data}, (res)=>{
          resolve(res);
        }, reject)
      })
    },
    on_change(row, i, data){
      Object.keys(data).forEach(k=>{
        console.log(`change: ${k}`, i, data[k]);
      })
      if (this.ban_change) return;
      if (row.num === 0){
        msg.confirm("是否删除").then(()=>{
          this.list.splice(i,1);
          ajax(`/home/cart/delete?ids=${row.id}`);
        }).catch(()=>{
          row.num = 1;
        })
      }
      console.log('on_change');
      this.compute_price();
    },
    select_list(){
      let res = [];
      this.list.forEach((row)=>{
        if (this.switch_stock && row.stock<=0) return;
        if (!row.status_bool) return;
        res.push(row);
      })
      return res;
    },
    compute_price(){
      let list = this.select_list();
      let cart_menu = {
        all_money: 0,
        vip_money: 0,
        promotion_money: 0,
        promotion_list: [],
        pay_money: 0,
        additional_money: 0,
        allon: this.count == list.length,
      }
      if (list.length){
        let data = list.map(row=>{
          let additional_select = {};
          Object.keys(row.additional_select).forEach((k)=>{
            additional_select[k] = row.additional_select[k]*1;
          })
          return {
            model_name: row.model_name,
            link_table: row.link_table,
            link_id: row.link_id*1,
            sku_id: row.sku_id*1,
            num: row.num*1,
            additional_select: additional_select,
          }
        })
        let data_json = JSON.stringify(data);
        if (data_json == this.compute_price_json) return;
        this.compute_price_json = data_json;
        ajax({url: '/home/cart/compute_price', data: {item: data}, method:"post", loading:true}, (res)=>{
          if (data_json != this.compute_price_json) return console.log(data.length);
          res.data.forEach((compute_price,i)=>{
            cart_menu.all_money += compute_price.all_money;
            cart_menu.vip_money += compute_price.vip_money;
            cart_menu.promotion_money += compute_price.promotion_money;
            cart_menu.pay_money += compute_price.pay_money;
            cart_menu.additional_money += compute_price.additional_money;

            if (list[i]) list[i].compute_price = compute_price;
          });
          this.cart_menu = cart_menu;
          this.ban_change = false;
        })
      }else{
        this.compute_price_json = '[]';
        this.cart_menu = cart_menu;
      }
    },
    all_select(on){
      this.list.forEach(v=>{
        let stock_pass = v.stock > 0 || !this.switch_stock;
        v.status_bool = (stock_pass && on);
        v.status = v.status_bool ? 1 : 0;
      });
    },
    buy(){
      let app = this;
      let list = this.select_list();
      if (!list.length) return msg.fail("至少选择一项");
      let s94_cart = new S94Cart(this.model_name, this.action, this.link_table);
      list.forEach(row=>{
        s94_cart.add_item(row);
      })
      s94_cart.to_buy();
    }
  },
  computed:{},
  mounted(){
    let app = this;

    let pay_model = S94Model.find(this.model_name);
    if (!pay_model || !pay_model["switch_pay"]) {
      msg(`参数错误：model_name=${this.model_name}`);
      return href_handle(-1, 1500);
    }
    if (!pay_model.action_map[this.action]) {
      msg(`参数错误：action=${this.action}`);
      return href_handle(-1, 1500);
    }

    let price_model = S94Model.find(this.link_table);
    if (!price_model || !price_model["switch_price"]) {
      msg(`参数错误：link_table=${this.link_table}`);
      return href_handle(-1, 1500);
    }

    this.switch_stock = !!price_model["switch_stock"];

    // 初始化
    this.init();
  }
}
</script>